<template>
  <page-meta :page-style="'overflow:'+(show?'hidden':'visible')"></page-meta>
  <view>
    <view class="choose-tab">
      <view class="choose-tab-item" :class="chooseTab == 0 ? 'activeOne' : ''" data-choose="0" @tap="clickTab">
        当前未处理({{repaircount}})
      </view>
      <view class="choose-tab-item" :class="chooseTab == 1 ? 'activeTwo' : ''" data-choose="1" @tap="clickTab">
        当前处理中({{zhengzaicount}})
      </view>
      <view class="choose-tab-item" :class="chooseTab == 2 ? 'activeThree' : ''" data-choose="2" @tap="clickTab">
        当前已处理({{wanchengcount}})
      </view>
    </view>

    <view class="content">
      <!--未处理的-->
      <block v-for="(item,i) in repairList" :key="i">
        <!--数据列表组件 -->
        <mypending :mypending="item"></mypending>
      </block>
    </view>
    <view>
      <!-- 输入框示例 -->
      <uni-popup ref="popup" background-color="#fff" :show='show' @change="popupchange">
        <view class="popup-content">
          <uni-table ref="table" :loading="loading" border stripe emptyText="暂无更多数据"
            @selection-change="selectionChange">
            <uni-tr>
              <uni-th width="80" align="center">昵称</uni-th>
              <uni-th align="center">手机号</uni-th>
              <uni-th width="100" align="center">操作</uni-th>
            </uni-tr>
            <uni-tr v-for="(item, index) in userList" :key="index">
              <uni-td align="center">
                <view class="name">{{ item.nickName }}</view>
              </uni-td>
              <uni-td align="center">{{ item.phonenumber }}</uni-td>
              <uni-td align="center">
                <view class="uni-group">
                  <button class="uni-button" size="mini" type="primary" @tap="clickUser(item.userId,item.nickName,item.phonenumber)">选择</button>
                </view>
              </uni-td>
            </uni-tr>
          </uni-table>
          <view class="uni-pagination-box"><uni-pagination show-icon :page-size="userqueryParams.pageSize"
              :current="userqueryParams.pageCurrent" :total="userTotal" @change="change" /></view>
        </view>
        <view class="btn_item">
          <button class="cancal" type="warn" @tap="close" size="mini">关闭</button>
        </view>
      </uni-popup>
    </view>
    <uni-popup ref="popupshow" background-color="#fff" :show='popshow' @change="popshowchange">
      <view class="repair-content">
        <uni-forms ref="form" :modelValue="formData" labelWidth="80px">
          <uni-forms-item label="维修描述:" name="repairDescription">
            <uni-easyinput type="textarea" v-model="formData.repairDescription"
              placeholder="请说明维修情况、更换了什么零件、后续应该注意什么事项" :maxlength="max" />
          </uni-forms-item>
          <uni-forms-item label="图片上传:" name="imgupload">
            <view class='right'>
              <view class="feedback-image-item" v-for="(item,index) in repairImgList" v-key="index">
                <view class="close-icon" @tap="delImg(index,item.id)">
                  <uni-icons type="closeempty" size="18" color="#fff"></uni-icons>
                </view>
                <view class="image-box">
                  <image :src="item.url" mode="aspectFill" @tap="previewImg(index,item.url)"></image>
                </view>
              </view>
              <view v-if="repairImgList.length < 5" class="feedback-image-item" @tap="addImage">
                <view class="image-box">
                  <uni-icons type="plusempty" size="50" color="#c7c7c7"></uni-icons>
                </view>
              </view>
            </view>
          </uni-forms-item>
        </uni-forms>
      </view>
      <view class="btn_item">
        <button type="warn" @tap="onclose" size="mini">关闭</button>
        <button @tap="submitForm" type="primary" size="mini">提交</button>
      </view>
    </uni-popup>
    <!--底部-->
    <myBottom :mybottom="repairList"></myBottom>
  </view>
</template>

<script>
  import {
    queryStateToList,
    selectCountByStatus,
    updateTask,
    addTaskState,
    sendScheduleMessage,
    sendMessage,
    uploadRepairImgAdd
  } from "@/api/system/task/task.js"
    import myBottom from '../components/my-bottom/my-bottom.vue';
    import mypending from '../components/my-pending/my-pending.vue';
  import {
    selectByRepairman
  } from "@/api/system/user.js";
  import getDateTime from '../../utils/getdateTime.js'
  import {
    getUserItme
  } from "@/api/system/user"

  export default {
    components: {
      myBottom,
      mypending
    },
    data() {
      return {
        //显示弹出框
        popshow: false,
        repairImgList: [],
        userId: null,
        //是否有弹框
        show: false,
        // 是否正在请求数据,节流阀
        isloading: false,
        // 查询参数
        repaircount: 0,
        zhengzaicount: 0,
        wanchengcount: 0,
        chooseTab: 0,
        statusOne: 0,
        statusTwo: 1,
        statusThree: 2,
        repairList: [],
        userList: [],
        // 数据总量
        userTotal: 0,
        maintenanceCode: null,
        warrantyPersonId: null,
        distributionType:null,
        urgency:null,
        loading: false,
        queryParams: {
          pageNum: 1,
          pageSize: 6,
          maintenanceStatus: 0,
          maintainerId: null
        },
        userqueryParams: {
          pageNum: 1,
          pageSize: 5
        },
        stateData: {
          maintenanceCode: null,
          state: "",
          datetime: getDateTime.dateTimeStr('y-m-d h:i:s'),
          descs: ""
        },
        returnCode: "",
        nickName: null,
        phonenumber: null,
        max: 500,
        formData: {
          maintenanceCode: '',
          repairDescription: "",
          maintenanceStatus: 2
        },
        rules: {
          repairDescription: {
            rules: [{
              required: true,
              errorMessage: '维修描述不能为空'
            }]
          },
        },
      }
    },
    //刚加载数据时
    onLoad(option) {
      this.userId = option.userid
      this.queryParams.maintainerId = (option.userid == 1) ? '' : option.userid
      this.queryStateList()
      this.queryNumberByState()
    },
    methods: {
      clickTab: function(e) { //点击切换
        if (!this.show) {
          this.chooseTab = e.target.dataset.choose;
          //重置关键数据
          this.empty()
          if (this.chooseTab == 0) {
            this.queryParams.maintenanceStatus = 0
          } else if (this.chooseTab == 1) {
            this.queryParams.maintenanceStatus = 1
          } else {
            this.queryParams.maintenanceStatus = 2
          }
          this.queryStateList()
          this.queryNumberByState()
        }
      },
      //清空
      onReady() {
        this.$refs.form.setRules(this.rules)
      },
      queryStateList(cb) {
        // 打开遮罩层
        this.$modal.loading("数据加载中...");
        // ** 打开节流阀
        this.isloading = true
        queryStateToList(this.queryParams).then(response => {
          if (response.code === 200) {
            // 关闭遮罩层
            this.$modal.closeLoading();
            uni.stopPullDownRefresh()
            // 关闭节流阀
            this.isloading = false
            // 只要数据请求完毕，就立即按需调用 cb 回调函数
            cb && cb()
            this.repairList = [...this.repairList, ...response.rows]
          }
        })
      },
      //查询各个状态数量
      queryNumberByState() {
        const data = {
          maintenanceStatus: this.statusOne,
          maintainerId: this.$auth.hasRole("admin") ? '' : this.userId
        }
        const datatwo = {
          maintenanceStatus: this.statusTwo,
          maintainerId: this.$auth.hasRole("admin") ? '' : this.userId
        }
        const datathree = {
          maintenanceStatus: this.statusThree,
          maintainerId: this.$auth.hasRole("admin") ? '' : this.userId
        }
        //查询未处理的
        selectCountByStatus(data).then(response => {
          this.repaircount = response.data
        })
        //查询正在处理的
        selectCountByStatus(datatwo).then(response => {
          this.zhengzaicount = response.data
        })
        //查询已完成的
        selectCountByStatus(datathree).then(response => {
          this.wanchengcount = response.data
        })
      },
      /**查询用户列表 */
      getuserList() {
        this.loading = true;
        selectByRepairman(this.userqueryParams).then(response => {
          this.userList = response.rows;
          this.loading = false;
        });
      },
      //弹窗时出现滑动穿透解决方案
      popupchange(e) {
        this.show = e.show
      },
      popshowchange(e) {
        this.popshow = e.popshow
      },
      //选择派发人员取消
      close() {
        // TODO 做一些其他的事情，before-close 为true的情况下，手动执行 close 才会关闭对话框
        this.$refs.popup.close()
      },
      //取消填写维修描述
      onclose() {
        this.$refs.popupshow.close()
      },
      //维修描述提交
      submitForm(ref) {
        this.$refs.form.validate().then(res => {
          //更新报修单
          this.formData.maintenanceCode = this.maintenanceCode
          updateTask(this.formData).then(response => {
            if (response.code === 200) {
              //上传图片
              if (this.repairImgList.length > 0) {
                this.repairImgList.forEach((item, index) => {
                  this.uploadimg(index, this.maintenanceCode)
                })
              }
              //判断有没有新增图片
              this.stateData.maintenanceCode = this.maintenanceCode
              this.stateData.state = "维修已完成(待审核)"
              addTaskState(this.stateData).then(response => {
                if (response.code == 200) {
                  getUserItme(this.warrantyPersonId).then(response => {
                    if (response.code == 200 && response.data.openId != null) {
                      //新增成功调用接口
                      const data = {
                        openid: response.data.openId,
                        selfPage: '/pages/login',
                        maintenanceCode: this.maintenanceCode,
                        maintenanceStatus: "维修已完成",
                        description: "维修人员已完成维修,请尽快去审核",
                      }
                      sendScheduleMessage(data).then(response => {
                        //操作成功跳转到已完成
                        this.chooseTab = 2
                        this.queryParams.maintenanceStatus = 2
                        //关闭弹窗
                        this.$refs.popupshow.close()
                        //重置关键数据
                        this.empty()
                        this.queryStateList()
                        this.queryNumberByState()
                        if (response.errcode == 0) {
                         this.$modal.msgSuccess("操作成功！")
                        } else {
                          this.$modal.msgError("订阅失败");
                        }
                      })
                    } else {
                      //操作成功跳转到已完成
                      this.chooseTab = 2
                      this.queryParams.maintenanceStatus = 2
                      //关闭弹窗
                      this.$refs.popupshow.close()
                      this.empty()
                      this.queryStateList()
                      this.queryNumberByState()
                      //重置关键数据
                      this.$modal.msgSuccess("操作成功！")
                    }
                  })
                }
              })
            }
          })
        })
      },
      //新增图片
      addImage() {
        const count = 5 - this.repairImgList.length
        uni.chooseImage({
          count: count, // 最多可以选择的图片张数，默认9
          sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
          sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
          success: (res) => {
            const tempFilePaths = res.tempFilePaths;
            tempFilePaths.forEach((item, index) => {
              if (index < count) {
                //处理小程序多选状况
                this.repairImgList.push({
                  url: item
                })
              }
            })
          },
        })
      },
      //删除图片
      delImg(index) {
        this.repairImgList.splice(index, 1)
      },
      //浏览图片
      previewImg(index, url) {
        const thant=this
        //每次点击浏览先清空数组
        thant.imglist = []
        //循环把路径丢到图片列表里面
        thant.repairImgList.forEach((item, index) => {
          thant.imglist.push(item.url)
        })
        uni.previewImage({
          urls: thant.imglist,
          current: url,
          // 下面我这边做的都是默认的选择
          longPressActions: {
            itemList: ['发送给朋友', '保存图片', '收藏'],
            success: function(data) {
              thant.$modal.msgSuccess(data)
            },
            fail: function(err) {
               thant.$modal.msgError(err)
            }
          }
        });
      },
      //这里触发图片上传的方法
      uploadimg(index, maintenanceCode) {
        //设备id，图片名称，路径
        let data = {
          repairImgCode: maintenanceCode,
          name: 'repairImg',
          filePath: this.repairImgList[index].url
        }
        //保存到数据库的方法调用
        uploadRepairImgAdd(data).then(response => {
          if (response.code != 200) {
            uni.showToast({
              title: "上传失败",
              icon: 'error'
            })
          }
        })
      },
      // 分页触发
      change(e) {
        this.userqueryParams.pageNum = e.current
        this.getuserList()
      },
      clickUser(userid,nickName,phonenumber) {
        if (this.maintenanceCode !== null && userid !== null) {
          this.$modal.confirm('确定派发该用户去维修吗？').then(() => {
            this.stateData.maintenanceCode = this.maintenanceCode
            this.stateData.state = this.distributionType==1?"维修中":'已重新派单，维修中'
            addTaskState(this.stateData).then(response => {
              if (response.code == 200) {
                const data = {
                  maintenanceCode: this.maintenanceCode,
                  maintenanceStatus: 1,
                  warrantyPersonId:this.warrantyPersonId,
                  maintainerId: userid,
                  startTime: getDateTime.dateTimeStr('y-m-d h:i:s')
                }
                updateTask(data).then(response => {
                  if (response.code === 200) {
                    getUserItme(userid).then(response => {
                      if (response.code == 200 && response.data.openId !=
                        null) {
                        //新增成功调用接口
                        const messagedata = {
                          openid: response.data.openId,
                          selfPage: '/pages/login',
                          maintenanceCode: this.maintenanceCode,
                          urgency: this.urgency == 0 ? '普通维修' : '紧急维修',
                          username: nickName,
                          phonenumber: phonenumber,
                          description: this.urgency == 0 ? '您有一份普通维修单,请在7天内及时处理' : '您有一份紧急维修单,请在3天内及时处理'
                        }
                        sendMessage(messagedata).then(response => {
                          //重置关键数据
                          //操作成功跳转到当前处理中
                          this.chooseTab = 1
                          this.queryParams.maintenanceStatus = 1
                          this.empty()
                          this.queryStateList()
                          this.queryNumberByState()
                          if (response.errcode == 0) {
                            this.$modal.msgSuccess("派发成功！")
                             this.$refs.popup.close()
                          } else {
                            this.$modal.msgError("订阅失败");
                             this.$refs.popup.close()
                          }
                        })
                      } else {
                        this.chooseTab = 1
                        this.queryParams.maintenanceStatus = 1
                        this.empty()
                        this.queryStateList()
                        this.queryNumberByState()
                        this.$modal.msgSuccess("派发成功！")
                        this.$refs.popup.close()
                      }
                    })
                  }
                })
              }
            })
          })
        }
      },
      //重置关键数据
      empty() {
        this.isloading = false
        this.repairList = []
        this.queryParams.pageNum = 1
      },
    },
    // 触底的事件
    onReachBottom() {
      if (this.chooseTab == 0) {
        // 判断是否还有下一页数据
        this.queryParams.maintenanceStatus = 0
        if (this.queryParams.pageNum * this.queryParams.pageSize >= this.repaircount) return uni.$showMsg('数据加载完毕')
      } else if (this.chooseTab == 1) {
        this.queryParams.maintenanceStatus = 1
        if (this.queryParams.pageNum * this.queryParams.pageSize >= this.zhengzaicount) return uni.$showMsg('数据加载完毕')
      } else {
        this.queryParams.maintenanceStatus = 2
        if (this.queryParams.pageNum * this.queryParams.pageSize >= this.wanchengcount) return uni.$showMsg('数据加载完毕')
      }
      // 判断是否正在请求其它数据，如果是，则不发起额外的请求
      if (this.isloading) return
      //让页码值自增+1
      this.queryParams.pageNum += 1
      // 重新获取列表数据
      this.queryStateList()
    },
    //下拉事件
    onPullDownRefresh() {
      this.empty()
      //重新发起数据请求
      this.queryNumberByState()
      this.queryStateList()
    },
  }
</script>

<style lang="scss">
  .choose-tab {
    background-color: #ffffff;
    display: flex;
    flex-flow: row;
    justify-content: space-between;
    width: 100%;
    position: sticky;
    top: 0;
    z-index: 999;
    height: 90rpx;
    line-height: 90rpx;
    text-align: center;
    border-top: 1rpx solid #dfdfdf;
  }

  .choose-tab-item {
    font-weight: bold;
    width: 33%;
  }

  .activeOne {
    color: #ee0a24;
    border-bottom: 4rpx solid #ee0a24;
  }

  .activeTwo {
    color: rgb(255, 170, 0);
    border-bottom: 4rpx solid rgb(255, 170, 0);
  }

  .activeThree {
    color: #07c160;
    border-bottom: 4rpx solid #07c160;
  }

  .content {
    margin: 20rpx;
    border-radius: 10rpx;
    position: relative;
  }

  .btn_item {
    display: flex;
    margin: 20rpx 0;
  }

  .repair-content {
    width: 350px;
    padding: 15px;

    .right {
      display: flex;
      flex-wrap: wrap;
      padding: 20rpx;

      .feedback-image-item {
        position: relative;
        width: 33.33%;
        height: 0;
        padding-top: 33.33%;
        box-sizing: border-box;

        .close-icon {
          display: flex;
          justify-content: center;
          align-items: center;
          position: absolute;
          top: 0;
          right: 0;
          width: 44rpx;
          height: 44rpx;
          border-radius: 50%;
          background-color: #ff5a5f;
          z-index: 2;
        }

        .image-box {
          display: flex;
          justify-content: center;
          align-items: center;
          position: absolute;
          top: 10rpx;
          right: 10rpx;
          left: 10rpx;
          bottom: 10rpx;
          border: 1px #c7c7c7 solid;
          border-radius: 10rpx;
          overflow: hidden;

          image {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
  }
</style>